#include "imgacquisitiontab.h"
#include "ui_imgacquisitiontab.h"

ImgAcquisitionTab::ImgAcquisitionTab(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ImgAcquisitionTab)
{
    ui->setupUi(this);

    ui->numImgComboBox->addItem("1");
    ui->numImgComboBox->addItem("2");
    ui->numImgComboBox->addItem("3");
    ui->numImgComboBox->addItem("4");
    ui->numImgComboBox->addItem("5");
    ui->numImgComboBox->addItem("6");
    ui->numImgComboBox->addItem("7");
    ui->numImgComboBox->addItem("8");
    ui->numImgComboBox->addItem("9");
    ui->numImgComboBox->addItem("10");


    ui->timeComboBox->addItem("4");
    ui->timeComboBox->addItem("5");
    ui->timeComboBox->addItem("6");
    ui->timeComboBox->addItem("7");
    ui->timeComboBox->addItem("8");
    ui->timeComboBox->addItem("9");
    ui->timeComboBox->addItem("10");

    connect(ui->pushButton_3, SIGNAL(clicked()), this, SLOT(scan()));
    connect(ui->liveButton, SIGNAL(clicked()), this, SLOT(liveview()));

}

ImgAcquisitionTab::~ImgAcquisitionTab()
{
    delete ui;
}

void ImgAcquisitionTab::addLoader(ImageLoader *imgL)
{
    if(imgL) this->imgL = imgL;
}

void ImgAcquisitionTab::showContent()
{
    QString file;

    if(this->imgL)
        file = imgL->getCurrFile();

    Mat img;

    if(file.length() > 0)
    {
        img = imread(file.toStdString());
        display(img);
    }
}


void ImgAcquisitionTab::scan()
{
    QMessageBox msgBox;
    msgBox.setText("CNC will start to scan at provided positions !!!");
    msgBox.exec();
}

void ImgAcquisitionTab::liveview()
{
    VideoCapture cap(0);
    if(!cap.isOpened()) return;

    Mat liveImg;
    namedWindow("live");

    while(true)
    {        
        cap >> liveImg;

        imshow("live", liveImg);
        display(liveImg);
        if(waitKey(1) > 0) break;
    }

    destroyWindow("live");
}

void ImgAcquisitionTab::display(const Mat &img)
{
    if(!img.data) return;

    Mat rgb;
    cvtColor(img, rgb, CV_BGR2RGB);

    QImage qTemp = QImage(rgb.data, rgb.cols, rgb.rows, rgb.step, QImage::Format_RGB888);
    if(qTemp.isNull()) return;
    else qTemp = qTemp.scaled(ui->imgLabel->size(), Qt::KeepAspectRatio);

    QPixmap pix = QPixmap::fromImage(qTemp, 0);

    // Set pix to be main pixmap
    ui->imgLabel->setPixmap(pix);
}
